package br.com.gip.repository.persistence;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

public abstract class HibernateDao<T, ID extends Serializable> implements Dao<T, ID>, Serializable {
	
	private static final long serialVersionUID = -6093966672156969384L;

	private Class<T> domainClass;

	@Resource
	private SessionFactory sessionFactory;
	
	@SuppressWarnings("unchecked")
	public HibernateDao() {
		this.domainClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}
	
	@Override
	public void delete(T entity) {
		this.sessionFactory.getCurrentSession().delete(entity);
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<T> findAll() {
		return (List<T>) this.sessionFactory.getCurrentSession().createCriteria(this.domainClass, "dc").list();
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public T findById(ID id) {
		return (T) this.sessionFactory.getCurrentSession().get(this.domainClass, id);
	}
	
	@SuppressWarnings("unchecked")
	public List<T> findByIds(List<ID> ids, String... sortingProperties) {
		Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(this.domainClass, "dc");
		criteria.add(Restrictions.in("dc.id", ids));
		criteria = this.addOrderingProperties(criteria, sortingProperties);
		return (List<T>) criteria.list();
	}

	@Override
	public void insert(T entity) {
		this.sessionFactory.getCurrentSession().save(entity);
	}

	@Override
	public void saveOrUpdate(T entity) {
		this.sessionFactory.getCurrentSession().saveOrUpdate(entity);
	}

	@Override
	public void saveOrUpdateAll(Collection<T> entities) {
		if (entities != null) {
			for (T entity : entities) {
				this.saveOrUpdate(entity);
			}
		}
	}
	
	@Override
	public void update(T entity) {
		this.sessionFactory.getCurrentSession().update(entity);
	}

	private Criteria addOrderingProperties(Criteria criteria, String... sortingProperties) {
		if (sortingProperties != null) {
			for (String orderingInfo : sortingProperties) {
				String[] propertyAndOrder = orderingInfo.split(":");
				String order = "asc";
				
				if (propertyAndOrder.length > 1) {
					order = propertyAndOrder[1];
				}
				
				if ("asc".equalsIgnoreCase(order)) {
					criteria.addOrder(Order.asc(propertyAndOrder[0]));
				} else {
					criteria.addOrder(Order.desc(propertyAndOrder[0]));
				}
			}
		}
		return criteria;
	}
	
	public Session getCurrentSession() {
		return this.sessionFactory.getCurrentSession();
	}

}
